<?php
class ExpertAction extends BaseAction
{
    public $token;
    public $wecha_id;
    public $expert_model;
	public $expert_level_model;
	public $expert_title_model;
	public $userinfo_model;
	public $consultation_model;
	public $userinfo;
	public $wxpay_config_model;
	public $alipay_config_db;
    
    /**
     * 构造函数
     */
    public function __construct(){
    
        $agent = $_SERVER['HTTP_USER_AGENT'];                                                                                                              
        if(!strpos($agent,"MicroMessenger")) {
            //	echo '此功能只能在微信浏览器中使用';exit;
        }
        
        $this->expert_model=M('Experts');
        $this->expert_level_model=M('Experts_level');
        $this->expert_title_model=M('Experts_title');
        $this->consultation_model=M('Consultation');
        $this->alipay_config_db = M('Alipay_m_config');
        $this->wxpay_config_model = M("wxpay_config");
                
        $this->userinfo_model = M('Userinfo');
    
        $this->token		= $this->_get('token');
        $this->assign('token',$this->token);
        $this->wecha_id	= $_SESSION['wecha_id'];
        //$_SESSION['wecha_id']	= 'oH2yOt67RVN5E-o-0uDGcgWAa1iQ';
        $this->assign('wecha_id',$this->wecha_id);
        
        $this->userinfo = $this->userinfo_model->where(array('token'=>$this->token,'wecha_id'=>$this->wecha_id))->find();
        $this->assign('userinfo',$this->userinfo);
        
        
        $config = $this->alipay_config_db->where(array(
            'token' => $this->token
        ))->find();
        $wx_config = $this->wxpay_config_model->where(array(
            'token' => $this->token
        ))->find();
        
        $this->assign('open',$config['open']);
        $this->assign('wxopen',$wx_config['open']);
        $this->assign('staticFilePath',str_replace('./','/',THEME_PATH.'common/css/product'));
    }
     
    /**
     * 主页
     */
    public function index()
    {
        if(!$_SESSION['wecha_id']){
            getCode("index",$this->token);
            return;
        }
        $userinfo = $this->userinfo_model->where(array('token'=>$this->token,'wecha_id'=>$this->wecha_id))->find();
	    $consultations = $this->consultation_model->where(array('userinfo_id'=>$userinfo['id']))->order('id desc')->limit(3)->select();
	    
	    foreach ($consultations as $ks=>$vs)
	    {
	        $consultations[$ks]['status'] = $this->consultationStatus($consultations[$ks]['status']);
	    }
	        
	    $where=array('token'=>$this->token,'auth_status'=>1);
	    $experts = $this->expert_model->where($where)->order('expert_id desc')->limit('10')->select();
	    
	    foreach($experts as $ks=>$vs)
	    {
	        $expert_level  = $this->expert_level_model->where(array('expert_id'=>$experts[$ks]['expert_id']))->find();
	        $experts[$ks]['expert_level'] = $expert_level['name'];
	    
	        $expert_title  = $this->expert_title_model->where(array('title_id'=>$experts[$ks]['title_id']))->find();
	        $experts[$ks]['expert_title'] = $expert_title['name'];
	    }
	    
	    $this->assign('experts',$experts);
	    $this->assign('consultations',$consultations);
        $this->display();
    }
    
    /**
     * 所有专家
     */
    public function experts(){
        $where=array('token'=>$this->token,'auth_status'=>1);// 只显示已认证的专家
        if (isset($_GET['level_id'])){
            $level_id=intval($_GET['level_id']);
            $where['level_id']=$level_id;
            	
            $thisLevel=$this->expert_level_model->where(array('level_id'=>$level_id))->find();
            $this->assign('thisLevel',$thisLevel);
        }
        
        if (isset($_GET['title_id'])){
            $title_id=intval($_GET['title_id']);
            $where['title_id']=$title_id;
             
            $thisTitle=$this->expert_title_model->where(array('title_id'=>$title_id))->find();
            $this->assign('thisTitle',$thisTitle);
        }
        
        if (IS_POST){
            $key = $this->_post('search_name');
            $this->redirect('/index.php?g=Wap&m=Expert&a=experts&token='.$this->token.'&keyword='.$key);
        }
        if (isset($_GET['keyword'])){
            $where['expert_name|personal_profile|technical_desc|keywords'] = array('like',"%".$_GET['keyword']."%");
            $this->assign('isSearch',1);
        }
        $count = $this->expert_model->where($where)->count();
        $this->assign('count',$count);
         
        $experts = $this->expert_model->where($where)->order('expert_id desc')->limit('10')->select();

        foreach($experts as $ks=>$vs)
        {
            $expert_level  = $this->expert_level_model->where(array('expert_id'=>$experts[$ks]['expert_id']))->find();
            $experts[$ks]['expert_level'] = $expert_level['name'];
            
            $expert_title  = $this->expert_title_model->where(array('title_id'=>$experts[$ks]['title_id']))->find();
            $experts[$ks]['expert_title'] = $expert_title['name'];
        }
        
        $this->assign('experts',$experts);
        $this->assign('metaTitle','专家教授');
        $this->display();
    }
    
    public function ajaxExperts(){
        $where=array('token'=>$this->token,'auth_status'=>1);
        if (isset($_GET['level_id'])){
            $level_id=intval($_GET['level_id']);
            $where['level_id']=$level_id;
        }
        
        if (isset($_GET['title_id'])){
            $title_id=intval($_GET['title_id']);
            $where['title_id']=$title_id;
        }
        
        $page=isset($_GET['page'])&&intval($_GET['page'])>1?intval($_GET['page']):2;
        $pageSize=isset($_GET['pagesize'])&&intval($_GET['pagesize'])>1?intval($_GET['pagesize']):10;
        $start=($page-1)*$pageSize;
        $experts = $this->expert_model->where($where)->order('expert_id desc')->limit($start.','.$pageSize)->select();

        foreach($experts as $ks=>$vs)
        {
            $expert_level  = $this->expert_level_model->where(array('expert_id'=>$experts[$ks]['expert_id']))->find();
            $experts[$ks]['expert_level'] = $expert_level['name'];
        
            $expert_title  = $this->expert_title_model->where(array('title_id'=>$experts[$ks]['title_id']))->find();
            $experts[$ks]['expert_title'] = $expert_title['name'];
        }
        
        $str='{"experts":[';
        if ($experts){
            $comma='';
            foreach ($experts as $p){
                $str.=$comma.'{"expert_id":"'.$p['expert_id'].'","expert_level":"'.$p['expert_level'].'","expert_title":"'.$p['expert_title'].'","expert_name":"'.$p['expert_name'].'","token":"'.$p['token'].'","keywords":"'.$p['keywords'].'","head_img":"'.$p['head_img'].'","reg_time":"'.$p['reg_time'].'"}';
                $comma=',';
            }
        }
        $str.=']}';
        $this->show($str);
    }
    
    /**
     * 专家详情
     */
    public function expertDetail()
    {
        $where=array('token'=>$this->token);
        if (isset($_GET['expert_id'])){
            $id=intval($_GET['expert_id']);
            $where['expert_id']=$id;
        }
        $expert=$this->expert_model->where($where)->find();
        $this->assign('expert',$expert);
         
        $this->assign('metaTitle',$expert['expert_name']);
        $expert['personal_profile']=str_replace(array('&lt;','&gt;','&quot;','&amp;nbsp;'),array('<','>','"',' '),$expert['intro']);
        $personal_profile=remove_html_tag($expert['personal_profile']);
        $personal_profile=mb_substr($personal_profile,0,30,'utf-8');
        $this->assign('personal_profile',$personal_profile);
        $this->display();
    }
    
    /**
     * 关注专家
     */
    public function collectExpert()
    {
        $data["wecha_id"] = $this->wecha_id;
        $data['token']=$this->token;
        $userinfo = $this->userinfo_model->where($data)->find();
        $where["user_id"] = $userinfo['user_id'];
        $where["expert_id"] =  $_GET['expert_id'];
        $user_collect = M("collect_experts")->where($where)->find();
        if($user_collect)
        {
            //已经存在关注记
            // 如果当前为关注，则取消关注
            if($user_collect['is_collect'] == 1)
            {
                $data['is_collect'] = 0;
            }
            else
            {
                $data["is_collect"] = 1;
            }
            M("collect_experts")->where($where)->save($data);
        }
        else
        {
            $data["user_id"] = $userinfo['user_id'];
            $data["expert_id"] =  $_GET['expert_id'];
            $data["add_time"] = time();
            $data["is_collect"] = 1;
            M("collect_experts")->add($data);
        }
        $this->ajaxReturn($data["is_collect"]);
    }
    
    /**
     * 我要咨询：选择咨询方式
     */
    public function  consultChooseType()
    {
        $this->assign('metaTitle','我要技术咨询');
        if($_POST)
        {
            $consult_type = $_POST['consult_type'];
            $this->redirect(U('Expert/consult',array('token'=>$this->token,'consult_type'=>$consult_type)));
        }
        else 
        {
            $this->display();
        }
    }
    
    /**
     * 我要咨詢
     */
    public function consult()
    {
        $consult_type = $_GET['consult_type'];
        if ($_POST)
        {
            import('ORG.UploadFile');
            $upload = new UploadFile();// 实例化上传类
            $upload->maxSize  = -1;// 设置附件上传大小
            $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $firstLetter=substr($this->token,0,1);
            $upload->savePath =  './uploads/'.$firstLetter.'/'.$this->token.'/';// 设置附件上传目录
            if($_FILES['consult_img']['name'])
            {
                if(!$upload->upload()) {// 上传错误提示错误信息
                    $this->error($upload->getErrorMsg());
                }else{// 上传成功 获取上传文件信息
                    $info =  $upload->getUploadFileInfo();
                    $consult_img = $info[0]['savepath'].$info[0]['savename'];
                }
            }
            
            $data['order_sn'] = get_order_sn();
            $data['userinfo_id'] = $this->userinfo['id'];
            $data['consult_type'] = $consult_type;
            $data['consult_desc'] = $_POST['consult_desc'];
            $data['consult_img'] = $consult_img;
            $data['consult_time'] = time();
            $data['token'] = $this->token;
            $data['status'] = 0;
            $data['consult_fee'] = $_POST['consult_fee'];
            $this->consultation_model->add($data);
            $consultation = $this->consultation_model->where($data)->find();
            $this->redirect(U('Expert/consultConfirm',array('token'=>$this->token,'order_sn'=>$data['order_sn'])));
        }
        else
        {
            $data['consult_type']=$_POST['consult_type'];
            $this->assign('consult_type',$consult_type);
            $this->display();
        }
    }
    
    /**
     * 支付
     */
    public function consultConfirm()
    {
        $order_sn = $_GET['order_sn'];
        $consultation = $this->consultation_model->where(array('order_sn'=>$order_sn))->find();
        $this->assign('consultation',$consultation);
        if ($_POST)
        {
            if($_POST["submit2"] == 'submit2')
            {
                $config = $this->wxpay_config_model->where(array('token' =>$this->token))->find();
                header("Location:".C('site_url')."/api/wxpay/wxpay.php?token=".$this->token."&wecha_id=".$this->wecha_id."&order_sn=".$order_sn."&total_fee=".$consultation['consult_fee']."&appid=".$config['appid']."&mchid=".$config['mchid']."&key=".$config['key']."&appsecret=".$config['appsecret']."&site_url=".C('site_url'));
                 
            }
            else if($_POST["submit1"] == 'submit1')
            {
                $this->redirect(U('Expert/alipay',array('order_sn'=>$order_sn,'token'=>$this->token)));
            }
        }
        else
        {
            // 竞标咨询里面是先支付
            $this->display();
        }
        
    }
    
    /**
     * 支付宝支付流程
     */
    public function alipay()
    {
        error_log("*******************alipay()*****************".$_GET['consult_id'],0);
        $order_sn = $_GET['order_sn'];
        $token = $_GET['token'];
        $this->assign('token',$token);
        $this->assign('order_sn',$order_sn);
        $this->display();
    }
    
    /**
     * 微信支付
     */
    public function wxpay(){
        $token=$_GET['token'];
        $order_sn=$_GET['order_sn'];
        $config = $this->wxpay_config_model->where(array('token' =>$this->token))->find();
        $order_info=$this->consultation_model->where(array('id'=>$order_sn))->find();
        error_log("ProductAction wxpay ==============================="."Location:".C('site_url')."/api/wxpay/wxpay.php?token=".$token."&order_sn=".$order_sn."&wecha_id=".$_SESSION['wecha_id']."&total_fee=".$order_info['consult_fee']."&appid=".$config['appid']."&mchid=".$config['mchid']."&key=".$config['key']."&appsecret=".$config['appsecret']."&site_url=".C('site_url'));
        header("Location:".C('site_url')."/api/wxpay/wxpay.php?token=".$token."&order_sn=".$order_sn."&wecha_id=".$_SESSION['wecha_id']."&total_fee=".$order_info['consult_fee']."&appid=".$config['appid']."&mchid=".$config['mchid']."&key=".$config['key']."&appsecret=".$config['appsecret']."&site_url=".C('site_url'));
    }
    
    /**
     * 支付成功页面
     */
    public function alipay_success(){
        error_log("************Product device_type = ".$_GET['device_type'],0);
        $this->display();
    }
    
    /**
     * 微信支付成功记录
     */
    public function addPayRecord()
    {
        error_log("***************ProductAction addPayRecord() *********************************");
        $outTradeNo = $_GET['outtradeno'];
        $transactionid = $_GET['transactionid'];
        $totalfee = $_GET['totalfee'];
        $tradestate = $_GET['tradestate'];
        $create_time = $_GET['create_time'];
        $consultation=$this->consultation_model->where(array('order_sn'=>$outTradeNo))->find();
        $consult_type = $consultation['consult_type'];
        error_log("***************ProductAction addPayRecord() *********************************consultation=".print_r($consultation,1));
        
        if($consultation)
        {
            if($consultation['status'] >= 2)
            {
                $this->success("该订单已经支付,请勿重复操作",U('Userinfo/consultationInfo',array('token'=>$consultation['token'],'id'=>$consultation['id'])));
            }
            else 
            {
                error_log("***************ExpertAction addPayRecord() *********************************type=".$consult_type);
                $this->consultation_model->where(array('order_sn'=>$outTradeNo))->save(array('status'=>2,'money_paid'=>$totalfee,'pay_time'=>time()));
                error_log("***************ProductAction addPayRecord() *********************************consultation2=".print_r($consultation,1));
                if ($consult_type == 2)
                {
                    error_log("******************|||||||||||||addPayRecord||||||||||||||||*********************consult_type = 2", 0);
                    $experts = $this->expert_model->order('expert_id desc')->limit('3')->select();
                    foreach ($experts as $e)
                    {
                        error_log("******************|||||||||addPayRecord||||||||||||||||||||*********************foreach expert_id =" . $e['expert_id'], 0);
                        $row['expert_id'] = $e['expert_id'];
                        $row['order_sn'] = $outTradeNo;
                      //  $row['pay_status'] = "1";
                        $row['pay_time']= time();
                        $row['pay_type']=2;//2 支付宝支付；1微信支付
                        $row['money_paid']=0;
                        $data['consult_id']=$consultation['id'];
                        $data['status']= 0;
                        $data['expert_id'] = $e['expert_id'];
                        error_log("******************|||||||||addPayRecord||||||||||||||||||||*********************row=".print_r($row,1), 0);
                        error_log("******************|||||||||addPayRecord||||||||||||||||||||*********************data=".print_r($data,1), 0);
                        if(M('Experts_solution')->add($data))
                        {
                            error_log("******************|||||||||addPayRecord||||||||||||||||||||*********************here2", 0);
                            $this->consultation_model->where(array('order_sn'=>$outTradeNo))->save(array('status'=>3));//咨询状态改为已分发
                
                        }
                         
                        error_log("******************|||||||||||||addPayRecord||||||||||||||||*********************Experts_solution=" . M('Experts_solution')->getLastSql(), 0);
                        M('Consult_payment')->add($row);
                        error_log("******************|||||||||||||addPayRecord||||||||||||||||*********************Consult_payment=" . M('Consult_payment')->getLastSql(), 0);
                    }
                
                }
                elseif ($consultation['consult_type'] == 1)
                {
                    // 指定专家
                }
                else
                {
                    //无偿
                }
                
            }
            
            $pay_record_model = M('pay_record');
            $pay_record = $pay_record_model->where(array('ordersn'=>$outTradeNo))->find();
            $row['ordersn']= $outTradeNo;
            $row['transactionid']= $transactionid;
            $row['totalfee']= $totalfee;
            $row['tradestate']= $tradestate;
            $row['paymethod']="wxpay";
            $time=strtotime($create_time);
            $row['createtime'] = $time;
            if($pay_record)
            {
                $pay_record_model->where(array('ordersn'=>$outTradeNo))->save($row);
            }
            else
            {
                $pay_record_model->add($row);
            }
            
        }
        
    }
    
    /**
     * 咨询状态转换  咨询状态：0 咨询问题保存；1 咨询待支付；2 咨询已支付；3 咨询已分发；4 咨询已抢答；5 咨询解答中；6 咨询追问；7 咨询结束；8 退款
     * @param unknown $st
     * @return string
     */
    public function consultationStatus($ct)
    {
        switch($ct) {
            case 1:
                $status = '咨询待支付';
                break;
            case 2:
                $status = '咨询已支付';
                break;
            case 3:
                $status = '咨询已分发';
                break;
            case 4:
                $status = '咨询已抢答';
                break;
            case 5:
                $status = '咨询解答中';
                break;
            case 6:
                $status = '咨询追问';
                break;
            case 7:
                $status = '咨询结束(取消)';
                break;
            case 8:
                $status = '咨询结束(已解答)';
                break;
            case 9:
                $status = '咨询结束(无解答)';
                break;
            case 10:
                $status = '咨询结束(提前)';
                break;
            case 11:
                $status = '申请退款';
                break;
            case 12:
                    $status = '已退款';
                    break;
            default:
                $status = '咨询问题保存';
                break;
        }

        return $status;
    }
    
    /**
     * auth 获取用户信息
     */
    public function auth(){
        $action=$this->_get('action');
        error_log("add by hutingting ExpertAction auth action***********************".$action,0);
        $code=$this->_get('code');
        $token=$this->_get('token');
        error_log("add by hutingting ExpertAction auth token***********************".$token,0);
        $pid = $this->_get('id');
        $diymen_set = M('diymen_set')->where(array('token'=>$token))->find();
        $wecha_id = getOpenid($code,$diymen_set['appid'],$diymen_set['appsecret']);
        $_SESSION['wecha_id']=$wecha_id;
        error_log("add by hutingting ExpertAction auth _SESSION[wecha_id]***********************".$_SESSION['wecha_id'],0);
        $userwhere['wecha_id'] = $wecha_id;
        $userwhere['token'] = $token;
        $_SESSION['token']  = $token;
        $jsondecode = isSubscribed($token,$wecha_id);
        $_SESSION['jsondecode'] = $jsondecode;
    
        // $userinfo = M('userinfo')->where($userwhere)->find();
        $userinfo = M('userinfo')->where(array('wecha_id'=>$wecha_id,'token'=>$token))->find();
        // 用户不存在--注册用户
        if(!$userinfo && $wecha_id)
        {
            $userdata['wecha_id'] = $wecha_id;
            $userdata['wechaname'] = randomkeys(6);
            $userdata['reg_time'] = time();
            $userdata['token'] = $_SESSION['token'];
            M('userinfo')->add($userdata);
            $userinfo =  M('userinfo')->where($userwhere)->find();
        }
    
        error_log("add by hutingting ExpertAction auth jsondecode***********************".print_r($jsondecode,1),0);
        $is_subscribe = $jsondecode->{"subscribe"};
        $_SESSION['is_subscribe']=$is_subscribe;
        $_SESSION['jsondecode']=$jsondecode;
        error_log("add by hutingting ExpertAction auth _SESSION[is_subscribe]***********************".$_SESSION['is_subscribe'],0);
        $nickname = $jsondecode->{"nickname"}."_".randomkeys(3);
        if(!$nickname)
        {
            $nickname = randomkeys(6);
        }
    
        if($is_subscribe)
        {
            if(!$userinfo['is_subscribe'])
            {
                // 关注（注册送积分）
                $subuserdata['wechaname'] = $nickname;
                $subuserdata['is_subscribe'] = 1;
                $userinfo = M('userinfo')->where($userwhere)->save($subuserdata);
                $userinfo = M('userinfo')->where($userwhere)->find();
            }
        }
    
        if($action == "cats"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Product&a=cats&token=".$token);
        }else if($action == "products"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Product&a=products&token=".$token."&catid=".$pid);
        }else if($action == "my"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Product&a=my&token=".$token);
        }else if($action == "cart"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Product&a=cart&token=".$token);
        }else if($action == "userinfo"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Userinfo&a=userinfo&token=".$token);
        }else if($action == "product"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Product&a=product&token=".$token."&id=".$pid);
        }else if($action == "confirmGroupOrder"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Product&a=confirmGroupOrder&token=".$token);
        }else if($action == "spinner"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Product&a=spinner&token=".$token);
        }else if($action == "asyncProducts"){
            header("Location:".C('site_url')."/index.php?g=Wap&m=Product&a=asyncProducts&token=".$token);
        }else{
            header("Location:".C('site_url')."/index.php?g=Wap&m=Expert&a=index&token=".$token);
        }
    }
}

?>